package com.xlongwei.light4j.handler.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.xlongwei.light4j.handler.ServiceHandler.AbstractHandler;
import com.xlongwei.light4j.util.HandlerUtil;
import com.xlongwei.light4j.util.NumberUtil;
import com.xlongwei.light4j.util.RedisConfig;
import com.xlongwei.light4j.util.StringUtil;

import io.undertow.server.HttpServerExchange;

public class PropertyHandler extends AbstractHandler {

	public void property(HttpServerExchange exchange) throws Exception {
		String type = StringUtil.firstNotBlank(HandlerUtil.getParam(exchange, "type"), "get");
		String cache = "property", key = HandlerUtil.getParam(exchange, "key");
		Map<String, Object> map = new HashMap<>();
		map.put("key", key);
		if (!StringUtil.isBlank(key)) {
			String value = HandlerUtil.getParam(exchange, "value");
			int expire = NumberUtil.parseInt(HandlerUtil.getParam(exchange, "expire"), 0);
			boolean keyHasCache = key.indexOf(':') > 0;
			if (keyHasCache) {
				cache = key.split("[:]")[0];
			}
			if (key.endsWith("*")) {
				Set<String> ks = RedisConfig.keys(keyHasCache ? key : cache + ":" + key);
				if ("set".equals(type) && key.contains(":")) {
					if ("delete".equals(value)) {
						for (String k : ks) {
							k = k.substring(k.indexOf(":") + 1);
							RedisConfig.delete(cache, k);
						}
					} else {
						if (expire > 0) {
							for (String k : ks) {
								k = k.substring(k.indexOf(":") + 1);
								RedisConfig.expire(cache, k, expire * 1000);
							}
						}
					}
					map.put("value", ks.size());
				} else {
					map.put("value", StringUtil.join(ks, null, "\n", null));
				}
			} else if ("get".equals(type)) {
				value = RedisConfig.get(cache, keyHasCache ? key.substring(cache.length() + 1) : key);
				map.put("value", value);
				if (value != null) {
					map.put("expire", RedisConfig.ttl(cache, keyHasCache ? key.substring(cache.length() + 1) : key));
				}
			} else {
				RedisConfig.set(cache, keyHasCache ? key.substring(cache.length() + 1) : key, value);
				if (value != null) {
					map.put("value", value);
					RedisConfig.expire(cache, keyHasCache ? key.substring(cache.length() + 1) : key, expire);
					map.put("expire", RedisConfig.ttl(cache, keyHasCache ? key.substring(cache.length() + 1) : key));
				}
			}
			HandlerUtil.setResp(exchange, map);
		}
	}
}
